package net.oschina.app.ui.detail;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomButtonsController;

import net.oschina.app.R;
import net.oschina.app.bean.Software;
import net.oschina.app.bean.SoftwareDetail;
import net.oschina.app.constant.Constants;
import net.oschina.app.databinding.FavoriteDetailActivityBinding;
import net.oschina.app.emoji.EmojiBody;
import net.oschina.app.emoji.MyPagerAdapter;
import net.oschina.app.util.EmoParser;
import net.oschina.app.util.MApp;
import net.oschina.app.util.TLog;
import net.oschina.app.util.UIUtils;
import net.oschina.app.util.URLGet;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import static net.oschina.app.R.id.emoji_ll;


/**
 * Created by YL on 2017/4/5.
 */
public class SoftDetailActivity extends AppCompatActivity {

    @BindView(R.id.btn_software_index)
    Button mBtnSoftwareIndex;
    @BindView(R.id.btn_software_document)
    Button mBtnSoftwareDocument;
    @BindView(R.id.btn_software_download)
    Button mBtnSoftwareDownload;
    @BindView(R.id.iv_text)
    ImageView mIvText;
    @BindView(R.id.iv_write)
    ImageView mIvWrite;
    @BindView(R.id.iv_opt_text)
    ImageView mIvOptText;
    @BindView(R.id.iv_favor)
    ImageView mIvFavor;
    @BindView(R.id.iv_report1)
    ImageView mIvReport1;
    @BindView(R.id.iv_report2)
    ImageView mIvReport2;
    @BindView(R.id.et_comment)
    EditText mEtComment;
    @BindView(R.id.iv_emoji)
    ImageView mIvEmoji;
    @BindView(R.id.iv_send_comment)
    ImageView mIvSendComment;
    @BindView(R.id.pager)
    ViewPager mPager;
    @BindView(R.id.emoji_tab)
    TabLayout mEmojiTab;
    @BindView(R.id.emoji_cancle)
    ImageView mEmojiCancle;

    private Toolbar favoritedetailtoolbar;
    private WebView mWebView;
    private View mView;
    private TextView mMsgCount;
    private LinearLayout mLl;
    private LinearLayout mLl_more;
    private boolean ischeck = true;
    private Software mSoftware;
    private boolean emojiIsVisible = false;
    private LinearLayout mEmoji_ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView = View.inflate(this, R.layout.favorite_detail_activity, null);
        setContentView(mView);
        ButterKnife.bind(this);
        initView();
        initWeb();
        //初始化emoji
        initEmoji();
        initEvent();
    }

    private void initEvent() {
        //当弹出软键盘并且emoji显示的时候
        mEtComment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b == true && mEmoji_ll.getVisibility() == View.VISIBLE) {
                    mEmoji_ll.setVisibility(View.GONE);
                }
            }
        });
        mEtComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                TLog.log("on"+charSequence.toString());
                TLog.log("on"+Thread.currentThread().getName());
                //mEtComment.setText(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                TLog.log("after"+editable.toString());

            }
        });
    }

    private void initEmoji() {
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(adapter);
        //设置接口回调
        adapter.setOnEmojiClickLitener(new EmojiBody.OnEmojiClickLitener() {
            @Override
            public void onclick(String str) {
                changeEdit(str);
            }
        });
    }

    private void changeEdit(String str) {
        String text = mEtComment.getText().toString();
        //获取光标所在位置
//        int index = mEtComment.getSelectionEnd();
        text += str;
        SpannableStringBuilder stringBuilder = EmoParser.parserEmoji(this, text);
//        if(index < mEtComment.getText().length()){
//        text.insert(index, stringBuilder);
//        }else {
//            text.append(stringBuilder);
//        }
        Log.d("xxx", text.toString());
        mEtComment.setText(stringBuilder);
    }

    private void initWeb() {
        URLGet urlGet = new URLGet();
        String url = getIntent().getStringExtra("url");
        url = Constants.SoftwareDetail + "/" + url.substring(url.lastIndexOf("/")) + ".xml";
        urlGet.getData(url, SoftwareDetail.class, new URLGet.OnURLGetLitener<SoftwareDetail>() {
            @Override
            public void showSuccess(SoftwareDetail bean) {
                Log.d("xxx", Thread.currentThread().getName());
                mSoftware = bean.getSoftware();
                MApp.mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        FavoriteDetailActivityBinding binding = DataBindingUtil.bind(mView);
                        binding.setSoftdetail(mSoftware);
                        binding.setImageUrl(mSoftware.getLogo());
                        if (mSoftware.getAuthor() == null) {
                            mView.findViewById(R.id.ll_author).setVisibility(View.GONE);
                        } else {
                            binding.setAuthor(mSoftware.getAuthor());
                        }

                        //推荐的隐藏于显示
                        if (true) {
                            mView.findViewById(R.id.iv_recommended).setVisibility(View.VISIBLE);
                        }
                        //显示消息的数量
                        mMsgCount.setText(mSoftware.getTweetCount() + "");

                        WebSettings settings = mWebView.getSettings();
                        settings.setDefaultFontSize(15);
                        //允许js效果
                        settings.setJavaScriptEnabled(true);
                        settings.setSupportZoom(true);
                        settings.setBuiltInZoomControls(true);
                        int sysVersion = Build.VERSION.SDK_INT;
                        if (sysVersion >= 11) {
                            settings.setDisplayZoomControls(false);
                        } else {
                            ZoomButtonsController zbc = new ZoomButtonsController(mWebView);
                            zbc.getZoomControls().setVisibility(View.GONE);
                        }
                        mWebView.setWebViewClient(new MyWebViewClient());
//                        String webViewBody = getWebViewBody(software);
                        mWebView.loadDataWithBaseURL(null, mSoftware.getBody(), "text/html", "utf-8", null);
                    }
                });
            }

            @Override
            public void showError(Exception e) {

            }
        });
//        String webViewBody = this.getWebViewBody(news);//添加内容
    }

    private void initView() {
        this.favoritedetailtoolbar = (Toolbar) findViewById(R.id.favorite_detail_toolbar);
        mWebView = (WebView) mView.findViewById(R.id.detail_webview);
        //消息数量action_comment_count
        mMsgCount = (TextView) mView.findViewById(R.id.action_comment_count);
        mLl = (LinearLayout) mView.findViewById(R.id.detail_toolbar);
        mLl_more = (LinearLayout) mView.findViewById(R.id.detail_toolbar_more);
        //emoji的视图
        mEmoji_ll = (LinearLayout) mView.findViewById(emoji_ll);
        //设置回退
        favoritedetailtoolbar.setNavigationIcon(R.drawable.actionbar_back_icon_normal);
        //设置title
        favoritedetailtoolbar.setTitle("软件详情");
        favoritedetailtoolbar.setTitleTextColor(Color.WHITE);

        setSupportActionBar(favoritedetailtoolbar);
        //设置监听
        favoritedetailtoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mEmojiTab.setupWithViewPager(mPager);
    }

    @OnClick({R.id.btn_software_index, R.id.btn_software_download, R.id.btn_software_document,
            R.id.iv_text, R.id.iv_write, R.id.iv_opt_text, R.id.iv_favor, R.id.iv_report1, R.id.iv_report2, R.id.iv_emoji, R.id.iv_send_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_software_index:
                if (mSoftware != null) {
                    startTo(mSoftware.getHomepage());
                }
                break;
            case R.id.btn_software_download:
                if (mSoftware != null) {
                    startTo(mSoftware.getDownload());
                }
                break;
            case R.id.btn_software_document:
                if (mSoftware != null) {
                    startTo(mSoftware.getDocument());
                }
                break;
            case R.id.iv_text:
            case R.id.iv_write:
                mLl.setVisibility(View.GONE);
                mLl_more.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_opt_text:
                View peedView = getWindow().peekDecorView();
                //关闭软键盘
                if (peedView != null) {
                    InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                //关闭emoji
                if (emojiIsVisible) {
                    mEmoji_ll.setVisibility(View.GONE);
                }
                mLl.setVisibility(View.VISIBLE);
                mLl_more.setVisibility(View.GONE);
                break;
            //收藏
            case R.id.iv_favor:
                Toast.makeText(this, "未登陆", Toast.LENGTH_SHORT).show();
                break;
            //分享
            case R.id.iv_report1:
                ShareSDK.initSDK(UIUtils.getContext(), "1c161cbe99e1e");
                showShare();
                break;
            case R.id.iv_report2:
                break;
            //表情
            case R.id.iv_emoji:
                if (mEmoji_ll.getVisibility() == View.GONE) {
                    mEmoji_ll.setVisibility(View.VISIBLE);
                    emojiIsVisible = true;
                } else {
                    mEmoji_ll.setVisibility(View.GONE);
                    emojiIsVisible = false;
                }
                break;
            //发送
            case R.id.iv_send_comment:
                String s = mEtComment.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    Toast.makeText(this, "信息不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void startTo(String url) {
        Intent intent = new Intent(this, SoftDetailMore.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//这里进行url拦截
            if (url != null) {
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();

// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("美女与野兽");
// titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
// text是分享文本，所有平台都需要这个字段
        oks.setText("究竟它们会发生什么样的故事呢");
// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
// site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
// siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }

    //动态添加,替换内容
    protected String getWebViewBody(Software mDetail) {
        StringBuffer body = new StringBuffer();
//        body.append(UIHelper.WEB_STYLE).append(UIHelper.WEB_LOAD_IMAGES);
        // 添加title
        //body.append(String.format("<div class='title'>%s</div>", mDetail.getTitle()));
        // 添加作者和时间
        //String time = StringUtils.friendly_time(mDetail.getPubDate());
//        String author = String.format("<a class='author' href='http://my.oschina.net/u/%s'>%s</a>", mDetail.getAuthorId(), mDetail.getAuthor());
//        body.append(String.format("<div class='authortime'>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</div>", author, time));
//        // 添加图片点击放大支持
//        body.append(setHtmlCotentSupportImagePreview(mDetail.getBody()));


        // 更多关于***软件的信息
//        String softwareName = mDetail.getSoftwareName();
//        String softwareLink = mDetail.getSoftwareLink();
//        if (!StringUtils.isEmpty(softwareName)
//                && !StringUtils.isEmpty(softwareLink))
//            body.append(String
//                    .format("<div class='oschina_software' style='margin-top:8px;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
//                            softwareLink, softwareName));

        // 相关新闻
//        if (mDetail != null && mDetail.getRelatives() != null
//                && mDetail.getRelatives().size() > 0) {
//            String strRelative = "";
//            for (News.Relative relative : mDetail.getRelatives()) {
//                strRelative += String.format(
//                        "<li><a href='%s' style='text-decoration:none'>%s</a></li>",
//                        relative.url, relative.title);
//            }
//            body.append("<p/><div style=\"height:1px;width:100%;background:#DADADA;margin-bottom:10px;\"/>"
//                    + String.format("<br/> <b>相关资讯</b><ul class='about'>%s</ul>",
//                    strRelative));
//        }
        body.append("<br/>");
        // 封尾
        body.append("</div></body>");
        return body.toString();
    }

}
